#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Created by jun_hua on 18-10-31 下午3:47
from flask import Flask, render_template, g
from config import Config, DevelopementConfig, ProductionConfig, config_map
from flask_sqlalchemy import SQLAlchemy
import redis
from Home.utils.commons import click_news_filter
from flask_wtf import CSRFProtect
from flask_session import Session
import logging  # 标准模块中的日志管理
from logging.handlers import RotatingFileHandler

logging.basicConfig(level=logging.DEBUG)  # 调试debug级
# 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
# 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
# 为刚创建的日志记录器设置日志记录格式
file_log_handler.setFormatter(formatter)
# 为全局的日志工具对象（flask app使用的）添加日志记录器
logging.getLogger().addHandler(file_log_handler)


db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    # 获取配置文件里面的key
    name = config_map.get(config_name)
    # 加载配置文件里面的DevelopementConfig,ProdutionConfig
    app.config.from_object(name)
    # 数据库对象初始化配置app对象
    db.init_app(app)

    # 开启CSRF保护,避免视图函数受到攻击
    CSRFProtect(app)
    # 开启session
    Session(app)

    from Home.Index import index_blue
    from Home.Admin import admin_blue
    from Home.passport import passport_blue
    from Home.news import news_blue
    from Home.user import user_blue

    app.register_blueprint(index_blue)
    app.register_blueprint(admin_blue)
    app.register_blueprint(passport_blue)
    app.register_blueprint(news_blue)
    app.register_blueprint(user_blue)

    app.add_template_filter(click_news_filter, 'index_filter')
    from flask_wtf.csrf import generate_csrf

    from Home.utils.commons import user_login_data

    @app.errorhandler(404)
    @user_login_data
    def error_404_handler(error):
        user = g.user

        data = {
            "user_info": user.to_dict() if user else None,

        }
        return render_template('news/404.html', data=data)

    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response
    return app


# 创建redis对象(用来存储验证码,图片验证码和短信验证码)
redis_store = redis.StrictRedis(host=Config.REDIS_HOST
                                , port=Config.REDIS_PORT
                                , decode_responses=True
                                # , password=Config.REDIS_PASSWORD
                                )


